//
//  SAStatisticalAddPayView.m
//  yidiantong
//
//  Created by 黄志刚 on 2021/1/12.
//

#import "SAStatisticalAddPayView.h"
#import "SATypeChooseColorCell.h"
#import "SAStatisticalAddPayModel.h"
#import "SAStatisticsExpendExpendTypeAPI.h"
#import "SAStatisticsExpendAddExpendTypeAPI.h"
#import "SAAddSpendingModel.h"
#import "SAStatisticsExpendDeleteExpendTypeAPI.h"
#import "GFAlertView.h"

@interface SAStatisticalAddPayView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate,HTTPAPIDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) SAStatisticsExpendExpendTypeAPI *statisticsExpendExpendTypeAPI;
@property (nonatomic, strong) SAStatisticsExpendAddExpendTypeAPI *statisticsExpendAddExpendTypeAPI;
@property (nonatomic, strong) NSMutableArray<SAStatisticalAddPayModel *> *payMarr;
@property (nonatomic, strong) UITextField *nameTf;
@property (nonatomic, strong) SAAddSpendingModel *model;
@property (nonatomic, strong) SAStatisticsExpendDeleteExpendTypeAPI *statisticsExpendDeleteExpendTypeAPI;
@property (nonatomic, strong) SAStatisticalAddPayModel *deleteModel;

@end


@implementation SAStatisticalAddPayView

+(instancetype)shareCornView {
    SAStatisticalAddPayView * shareView = [[SAStatisticalAddPayView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [shareView creatUI];
    return shareView;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.statisticsExpendAddExpendTypeAPI == api) {
        self.nameTf.text = @"";
        [self.statisticsExpendExpendTypeAPI sendRequestToServerWithActivityViewAndMask:POST];
    }else if (self.statisticsExpendExpendTypeAPI == api) {
        self.payMarr = [SAStatisticalAddPayModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        [self.collectionView reloadData];
    }else if (self.statisticsExpendDeleteExpendTypeAPI == api) {
        SAStatisticalAddPayModel *deleteModel = nil;
        for (SAStatisticalAddPayModel *model in self.payMarr) {
            if ([model.expendAttrId isEqualToString:self.statisticsExpendDeleteExpendTypeAPI.expendAttrId]) {
                deleteModel = model;
            }
        }
        if (deleteModel != nil) {
            [self.payMarr removeObject:deleteModel];
            [self.collectionView reloadData];
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
 
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.payMarr.count;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier=@"SATypeChooseColorCell";
    SATypeChooseColorCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [cell payModel:self.payMarr[indexPath.row]];
    if (indexPath.section == 0) {
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(moveCollectionViewCell:)];
        [cell addGestureRecognizer:longPress];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    for (SAStatisticalAddPayModel *list in self.payMarr) {
        list.check = NO;
    }
    SAStatisticalAddPayModel *list = self.payMarr[indexPath.row];
    list.check = YES;
    [self.collectionView reloadData];
}

-(void)loadData:(NSMutableArray *)payMarr AndPayModel:(SAAddSpendingModel *)model {
    self.payMarr = payMarr;
    if (model == nil) {
        for (SAStatisticalAddPayModel *payModel in self.payMarr) {
            payModel.check = NO;
        }
    }else {
        for (SAStatisticalAddPayModel *payModel in self.payMarr) {
            if ([payModel.expendAttrId isEqualToString:model.expendAttrId]) {
                payModel.check = YES;
            }else {
                payModel.check = NO;
            }
        }
    }
    self.model = model;
    [self.collectionView reloadData];
}

#pragma mark - event
-(void)clickedAddBtn {
    if (trimString(self.nameTf.text).length == 0) {
        [Prompt popPromptViewWithMsg:@"请输入类别名称" duration:2];
        return;
    }
    [self endEditing:YES];
    self.statisticsExpendAddExpendTypeAPI.attrName = trimString(self.nameTf.text);
    [self.statisticsExpendAddExpendTypeAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)clickedDeleteBtn {
    [self shareDissTapEvent];
}

-(void)clickedConfirmBtn {
    SAStatisticalAddPayModel *model = nil;
    for (SAStatisticalAddPayModel *list in self.payMarr) {
        if (list.check == YES) {
            model = list;
        }
    }
    if (model == nil) {
        [Prompt popPromptViewWithMsg:@"请选择一个类别" duration:2];
        return;
    }
    
    if (self.model == nil) {
        !self.selectBlock ?: self.selectBlock(model);
    }else {
        !self.editBlock ?: self.editBlock(model);
    }
    
    [self confirmationTapEvent];
}

#pragma mark - 手势事件
-(void)moveCollectionViewCell:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            CGPoint point = [gesture locationInView:self.collectionView];
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
            if (indexPath.section != 0) {
                return;
            }
            self.deleteModel = self.payMarr[indexPath.row];
            GFAlertView *alertView = [GFAlertView alertViewWithMsg:@"提示" detailMsg:@"确认删除该类别?" knowBtnBlock:^(UIButton *knowBtn) {
                [knowBtn addTarget:self action:@selector(deletePayModel) forControlEvents:UIControlEventTouchUpInside];
            }];
            [alertView showWithAnimation];
        }
        case UIGestureRecognizerStateChanged: {
            break;
        }
        case UIGestureRecognizerStateEnded: {
        }
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

-(void)deletePayModel {
    SAStatisticalAddPayModel *model = self.deleteModel;
    self.statisticsExpendDeleteExpendTypeAPI.expendAttrId = model.expendAttrId;
    [self.statisticsExpendDeleteExpendTypeAPI sendRequestToServerWithActivityViewAndMask:POST];
}

#pragma mark - initUI
-(void)creatUI {
    self.backgroundColor = kColor(0, 0, 0, 0.3);
    UIView *backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(510), kScreenWidth, kScaleNum(510))];
    backGroundView.backgroundColor = [UIColor whiteColor];
    backGroundView.userInteractionEnabled = YES;
    [self addSubview:backGroundView];
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(0, 0, kBaseScreenWidth, kScreenHeight -  kScaleNum(510));
    [deleteBtn addTarget:self action:@selector(clickedDeleteBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:deleteBtn];
    
    UIView *grayView = [[UIView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth, 44)];
    grayView.backgroundColor = kLineColor;
    [backGroundView addSubview:grayView];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = SARectMake(kBaseScreenWidth - 60, 0, 60, 44);
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = kFont(15);
    [confirmBtn addTarget:self action:@selector(clickedConfirmBtn) forControlEvents:UIControlEventTouchUpInside];
    [backGroundView addSubview:confirmBtn];
    
    UITextField *nameTf = [[UITextField alloc] initWithFrame:SARectMake(30, 44, 200, 50)];
    nameTf.placeholder = @"请输入类别名称";
    nameTf.font = kFont(15);
    nameTf.textAlignment = NSTextAlignmentLeft;
    nameTf.tintColor = kBuleColor;
    [backGroundView addSubview:nameTf];
    self.nameTf = nameTf;
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = SARectMake(kBaseScreenWidth - 65, 51, 50, 36);
    [addBtn setBackgroundImage:[UIImage imageNamed:@"SA_btn_pink"] forState:UIControlStateNormal];
    [addBtn setTitle:@"新增" forState:UIControlStateNormal];
    [addBtn setTitleColor:kPinkColor forState:UIControlStateNormal];
    addBtn.titleLabel.font = kFont(15);
    [addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [backGroundView addSubview:addBtn];
    
    UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 94, kBaseScreenWidth, 1)];
    line.backgroundColor = kLineColor;
    [backGroundView addSubview:line];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.itemSize = CGSizeMake(kScaleNum(80), kScaleNum(30));
    flow.minimumLineSpacing = kScaleNum(15);
    flow.minimumLineSpacing = kScaleNum(15);
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(15), kScaleNum(110), kScreenWidth - kScaleNum(30), kScaleNum(510) - kScaleNum(110)) collectionViewLayout:flow];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [backGroundView addSubview:_collectionView];
    [_collectionView registerClass:[SATypeChooseColorCell class] forCellWithReuseIdentifier:@"SATypeChooseColorCell"];
}

- (void)showView:(UIViewController *)Sview
{
    if(Sview == nil){
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }else{
        [Sview.view addSubview:self];
    }
}

-(void)shareDissTapEvent {
    !self.updateMarr ?: self.updateMarr(self.payMarr);
    [UIView animateWithDuration:0.5f animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)confirmationTapEvent {
    [self shareDissTapEvent];
}

-(SAStatisticsExpendExpendTypeAPI *)statisticsExpendExpendTypeAPI {
    if (!_statisticsExpendExpendTypeAPI) {
        _statisticsExpendExpendTypeAPI = [SAStatisticsExpendExpendTypeAPI apiWithDelegate:self];
    }
    return _statisticsExpendExpendTypeAPI;
}

-(SAStatisticsExpendAddExpendTypeAPI *)statisticsExpendAddExpendTypeAPI {
    if (!_statisticsExpendAddExpendTypeAPI) {
        _statisticsExpendAddExpendTypeAPI = [SAStatisticsExpendAddExpendTypeAPI apiWithDelegate:self];
    }
    return _statisticsExpendAddExpendTypeAPI;
}

-(SAStatisticsExpendDeleteExpendTypeAPI *)statisticsExpendDeleteExpendTypeAPI {
    if (!_statisticsExpendDeleteExpendTypeAPI) {
        _statisticsExpendDeleteExpendTypeAPI = [SAStatisticsExpendDeleteExpendTypeAPI apiWithDelegate:self];
    }
    return _statisticsExpendDeleteExpendTypeAPI;
}


@end
